// pages/conference/input_second.js
import {my_showToast_ok,my_request,my_showToast_error,gen_query_str} from '../../utils/my_utils'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    back_url:"/pages/conference/input_first",
    next_url:"/pages/conference/input_third",
    show_local_image:false,
    local_image_path:"",
    uploading:false,
    init_warning_danger:{
      long_summary:"",
    },
    submit_data_length:{},
    maxlength:{
      long_summary:500,
    },
    must_fields:[
      {
        key:'long_summary',
        value:"会议详情",
      },
      {
        key:"cover",
        value:"封面"
      }
    ],
    submit_data:{}
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if(!options.edit_id){
      my_showToast_error("逻辑错误",2000)
    }
    this.save_props(options);
    if(!this.load_cache()){
      console.log('load from server')
      this.load_conference(+options.edit_id);
    }
  },
  choose_image:function(){
    var that=this;
    wx.chooseImage({
      count: 1, // 默认9
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function (res) {
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        var tempFilePaths = res.tempFilePaths
        that.setData({
          show_local_image:true,
          local_image_path:tempFilePaths,
          uploading:true
        })
        if(!that.data.query_data.edit_id){
          my_showToast_error("逻辑错误",2000)
          return
        }
        var complete_func=function(cover_link){
          var submit_data=that.data.submit_data;
          submit_data.cover=cover_link
          that.setData({
            submit_data:submit_data,
            uploading:false
          })
        }
        getApp().getUpToken(function (upToken) {
          that.onePost(tempFilePaths, 
            0, 
            tempFilePaths.length,
            that.data.query_data.edit_id,
            complete_func,
            upToken
          );
        })
      }
    })
  },

  onePost: function (flie, i, n,conference_id,on_complete,upToken) {
    console.log(flie)
    var that = this;
    var key = "abcdefgabc_conference_"+conference_id+'_'+Date.parse(new Date());
    wx.uploadFile({
      url: 'https://up.qbox.me',
      filePath: flie[i],
      name: 'file',
      formData: {
        'token': upToken,
        'key': key
      },
      success: function (r) {
        console.log(r)
        var data = r.data;
        if (typeof data === 'string') data = JSON.parse(data.trim());
        if (data.key) {
          var upImg="https://blhd.1demo.com/" + key
          
          on_complete(upImg);
        }
      },
      fail:function(){
        console.log("fail")
      },
      complete:function(r){
        console.log("complete",r)
      }
    })
  },

  input_text:function(e){
    var var_name = e.currentTarget.dataset.name;
    var max_length = +e.currentTarget.dataset.maxlength;
    var value = e.detail.value;
    var cursor = e.detail.cursor;
    var submit_data = this.data.submit_data;
    var submit_data_length = this.data.submit_data_length;
    submit_data[var_name] = value;
    submit_data_length[var_name]=value.length;
    this.setData({
      submit_data:submit_data,
      submit_data_length:submit_data_length
    })
  },
  valid_submit_data:function(){
    var submit_data = this.data.submit_data;
    var must_fields = this.data.must_fields
    var key="";
    var desc="";
    for(var i=0;i<must_fields.length;++i){
      key = must_fields[i].key;
      desc= must_fields[i].value;
      if(!submit_data[key]){
        var warning_danger = {...this.data.init_warning_danger}
        //console.log(warning_danger)
        warning_danger[key]="danger"
        this.setData({
          warning_danger:warning_danger
        })
        my_showToast_error("输入错误",2000)
        return false;
      }
    }
    return true;
  },
  save_props:function(options){
    var query_data={...options};
    query_data.back="cache"
    this.setData({
      query_data:query_data
    })
  },
  add_props:function(key,value){
    var query_data = {...this.data.query_data};
    query_data[key]=value;
    this.setData({
      query_data:query_data
    });
  },
  change_step:function(go_url){
    var query_data={...this.data.query_data};
    var jump_url=go_url+gen_query_str(query_data);
    console.log("second_step:"+jump_url);
    wx.redirectTo({
      url:jump_url
    })
  },
  load_cache:function(){
    var cache=wx.getStorageSync("second-step-cache");
    if(!cache){
      //my_showToast_error("逻辑错误",2000)
      return false
    }
    if(cache.edit_id==this.data.query_data.edit_id){
      console.log(cache.publisher)
      //if(!isNumber(praseInt(cache.publisher))){
      //  return false
      //}
      this.add_props("publisher",cache.publisher)
      this.setData({
        submit_data:{...cache.submit_data},
        init_submit_data:{...cache.submit_data},
      })
      if(cache.submit_data.cover){
        this.setData({
          show_local_image:true,
          local_image_path:cache.submit_data.cover
        })
      }
      return true
    }
    return false
  },
  save_cache:function(){
    var cache={};
    cache.submit_data=this.data.submit_data;
    cache.edit_id = this.data.query_data.edit_id;
    cache.publisher = +this.data.query_data.publisher
    wx.setStorageSync("second-step-cache",cache);
  },
  check_update:function(){
    var submit_data=this.data.submit_data;
    var init_submit_data=this.data.init_submit_data;
    for(var key in submit_data){
      if(submit_data[key]!=init_submit_data[key]){
        return true
      }
    }
    for(var key in init_submit_data){
      if(init_submit_data[key]!=submit_data[key]){
        return true
      }
    }
    return false
  },
  load_conference:function(id){
    var that=this;
    this.setData({
      loading:true
    })
    var conference_data=wx.getStorageSync("current-edit-conference");
    if(conference_data){
      if(this.data.query_data.edit_id==conference_data.id){
        var transformed_data=that.transform_meeting_data(conference_data);
        var submit_data={};
        submit_data.cover=transformed_data.cover;
        submit_data.long_summary=transformed_data.long_summary;
        that.add_props("publisher",transformed_data.creat_identity_id);
        this.setData({
          submit_data:submit_data,
          init_submit_data:{...submit_data},
          loading:false
        })
        return
      }
    }
    //没有找到缓存
    my_request({
      url: 'https://sichuangyi.demopp.in/api-conference-alpha/conference-detail',
      method: "GET",
      data: {
        meeting_id: id
      },
      success:function(res){
        var conference_data=res.data.data.conference;
        wx.setStorageSync("current-edit-conference",conference_data);
        var transformed_data=that.transform_meeting_data(conference_data);
        var submit_data={};
        submit_data.cover=transformed_data.cover;
        submit_data.long_summary=transformed_data.long_summary;
        that.add_props("publisher",transformed_data.creat_identity_id);
        that.setData({
          submit_data:submit_data,
          init_submit_data:{...submit_data},
          loading:false
        })
        if(submit_data.cover){
          that.setData({
            show_local_image:true,
            local_image_path:submit_data.cover
          })
        }
      }
    })
  },
  transform_meeting_data:function(conference_data){
    var transformed_data={};
    if(conference_data.meeting_name){
      transformed_data.conference_name = conference_data.meeting_name
    }
    if(conference_data.short_summary){
      transformed_data.conference_intro = conference_data.short_summary
    }
    if(conference_data.meeting_time){
      var two_parts = conference_data.meeting_time.split(' ');
      transformed_data.date=two_parts[0];
      transformed_data.time=two_parts[1].split(':').slice(0,2).join(':');
    }
    if(conference_data.region){
      transformed_data.region=conference_data.region
    }
    if(conference_data.meeting_address){
      transformed_data.conference_location=conference_data.meeting_address
    }
    if(conference_data.long_summary){
      transformed_data.long_summary=conference_data.long_summary
    }
    if(conference_data.cover){
      transformed_data.cover=conference_data.cover
    }
    if(conference_data.creat_identity_id){
      transformed_data.creat_identity_id=conference_data.creat_identity_id
    }
    return transformed_data
  },
  save_to_server:function(){
    if(!this.data.query_data.edit_id){
      my_showToast_error("逻辑错误",2000);
      return
    }
    var that=this;
    var request_data={
      publisher:+this.data.query_data.publisher,
      step:2,
      data:that.data.submit_data,
      meeting:+this.data.query_data.edit_id
    };
    my_request({
      url:"https://sichuangyi.demopp.in/api-conference-alpha/submit",
      method:"POST",
      data:request_data,
      success:function(res){
        console.log(res);
        my_showToast_ok("保存成功",2000)
      },
      fail:function(res){
        my_showToast_error("保存失败",2000);
      },
      complete: function() {
        wx.removeStorageSync("current-edit-conference")
      }
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
  
  },

  

  go_to_next:function(){
    this.save_cache();
    if(this.valid_submit_data()){
      if(this.check_update()){
        this.save_to_server()
      }
      this.change_step(this.data.next_url)
    }
  },
  go_back:function(){
    this.save_cache();
    this.change_step(this.data.back_url)
  }
})